package com.fks.fks_service.utils.aliutils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundAuthOrderAppFreezeRequest;
import com.alipay.api.response.AlipayFundAuthOrderAppFreezeResponse;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

public class FreeOfCharge {

    public static String privateKey  = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIB" +
            "AQCQEzgoC7Rdpq7FrsiE7UXjz0yn32VPbcPpSXtg+wiqyo7op0ex9T+7h/jam49vz" +
            "pmp/Ka0zE27P5YqsbJHO90G9jeLw0548Swo4e3sJZQ2403t+OOMbJnNCzCJvmAQ1aeCc" +
            "QsVSfvucsUU3N37BrGeCwqfTDlEijAP9SQHfzJ8TCY5FWT2PTEg7A79fcJh91TFDf3nV" +
            "SA6gxxi+7DRKxY3YydtyTnye6rr6/vDQWUk6pW1s4G6ftrJKs4KfJnKE1WD9zd8xvD5c" +
            "WNObkigVF/sV9JFOaGXgDDrlNj8vCoE9cehHq5kQZT4tl9eRoCmHJ0H0Bor7nitNe8EaS1" +
            "01HotAgMBAAECggEAeZOuVKSj3E9Wtjwqu3kZ/AYnUpXCAQfIRWkbsxfDFZR+ibb3WiVxV" +
            "YeFKLwSiy/VHcu0xWaNxY//4SE4JsJOXpyQ/OCfrJEfSZR1WEvRyYuAbGsVYZ8XHh7uI55B" +
            "pJMWmo1X4+wdqvawdk13CGh6o7n/ibMhtEPEEQM1Fxpv+NBoHuivLRVwu5fszWbTrzU+Kldp" +
            "xMiE9cVR6uQ4Ha207Y+lfdVqgOd+WXNydxqPIbfTCiAidC9+Ic0SI1F+/M+/u6TQx4AseC6o" +
            "BuLf/xNl4RVMccym/OWm6Dp3x1h9vPvVORJaZcKAhyQnDYZRjyy6uKPwuQJY1Wb25ZOIaQpm" +
            "4QKBgQDR1rtEpj0LlxOvE7td2ctBa9lDvQfH1QNcTHfX7rG3+wFMh2L3DYYVBkqKIpCgQxsbr" +
            "PEDRFaEDOqRbgtb3CvXr526ViZzmYGpQllfdL8HHq8imFIyclq5sC+PJ7YYHSlWkUvtckcPOm" +
            "S5wErK4a2bWb9zL/WJDwxnmUD0M3W6hQKBgQCvxPE8f/RhZX6y8VkazhNgvk01r4w9xgSWOf3" +
            "LcUDNkofdKVAN4Y6WkFdpdaK6ZDE6tYm5sE2hAJtpItWd3pQm/v6RX6u73E3q5R1mqfH4ObMyQ9" +
            "Cmp2/kdaCWH88tqLTrpzkEL6prjdAKxcEXkUWn4lCLmC3dfwv2PqDceQfViQKBgQDIFtXjFBFJp" +
            "/mhDFOxnifubgRyTyHILxpRPKlaQcU9Bh+q9b4sjby495LEPUljSBnlPfdjghptOFPD8QbrxPoZ" +
            "ZOAl+lgYCtxUpWvLVeuBwoSFnHFkoR5ZyeLPwrIkNEpivZGFDV8s6iV56h5nbuK4K9Ae6jBbTPo" +
            "rHzuMoDU2cQKBgQCuJN6phVB3itpLqikREKlMSV8v2HyG24DB4jTccpm00v+/E+ZXymi+LcYdG0q" +
            "dhxTrSN9qVQ2kfXh8YuHoJpT8Sdmn6HS6jJu6JUPK6ods2qX7IAtCglOuswfmlR9r6mFNtQEdb6h" +
            "WJUvA0IrtsaWknuoUVDLk57HPR9+ScGtdmQKBgDtDGfzMmpv0bzjf6jSQbTQLKiTq+qcbqQ1WMlu" +
            "LFTQpnYr8zmV3r2J7iSv1e6L1OZC1D8pe24K3tzQ1mYUqhIUMMpjiK6u1q8Jykj0ty6pUtuHwo0t" +
            "DSD8xyCNU6g86rEAhrUlN4qrYUZn6KVHLu5guFjcq9n0ss4BYqjg3pVqd";
    public static String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApabY3/oQLwaw3ugYnr" +
            "bP0XC4ox/NkT6M4/nKEvxMcZ6+bbnNoCdTVm2BzAoSX7oOfn8vmfGnmELgwVtRp+VHuLoNS0jLuUCDQ" +
            "qzwJP2RxF+3EYFrvCU9Ykukj2SvqRxr+OTkh1zLNT6EWMkjYTsBlaHgJA9LmnVz8UV3DG+4sLpy8zTf" +
            "+6iS8HD1bHqtVo4NU/WjOuEdNy7Dv0Va1h/8KxMnCkhfS5ZmKiYB40Lci/Qou/B074DPbsE3MDGb8Hj" +
            "J7mH05FjKUUjsmi/HEa6Nn/pfk7cSG/j41hyDH8wQR21UN2+8IhuxjnhGs6ohr1MqjLiZuYFo67oL5AWSyBVQLQIDAQAB";


    public static String freeCharge(Map<String,String> map) throws JSONException, AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","2021004132618212",privateKey,"json","UTF-8",alipayPublicKey,"RSA2");
        AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
        // 设置异步通知
        request.setNotifyUrl("http://r3ae87.natappfree.cc/api/alipayNotify");

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_order_no",map.get("out_order_no"));
        bizContent.put("out_request_no",map.get("out_request_no"));
        bizContent.put("order_title",map.get("order_title"));
        bizContent.put("amount",map.get("amount"));
        bizContent.put("product_code",map.get("product_code"));
        bizContent.put("payee_user_id","2088641109330614");
        bizContent.put("timeout_express",map.get("timeout_express"));

        //JSONObject bizContent = new JSONObject();
        //bizContent.put("out_order_no","outOrderNo123");
        //bizContent.put("out_request_no","outRequestNo123");
        //bizContent.put("order_title","XX租车押金");
        //bizContent.put("amount",0.01);
        //bizContent.put("product_code","PRE_AUTH_ONLINE");
        //bizContent.put("payee_user_id","2088102000275795");
        //bizContent.put("timeout_express","30m");

        //JSONArray disablePayChannels = new JSONArray();
        //// 禁用渠道添加信用卡快捷
        //JSONObject disableChannel1 = new JSONObject();
        //disableChannel1.put("payChannelType","OPTIMIZED_MOTO");
        //disablePayChannels.add(disableChannel1);
        //// 禁用渠道添加信用卡卡通
        //JSONObject disableChannel2 = new JSONObject();
        //disableChannel2.put("payChannelType","BIGAMOUNT_CREDIT_CARTOON");
        //disablePayChannels.add(disableChannel2);
        //// 设置禁用渠道(无特殊诉求请勿传入)
        //bizContent.put("disable_pay_channels",disablePayChannels);

        //// 买家实名信息（无特殊诉求请勿传入）
        //JSONObject identityParams = new JSONObject();
        //String identityHash = genHashCode("SHA-256","UTF-8","张三","4566498798498498498498");
        //identityParams.put("identity_hash",identityHash);
        //identityParams.put("alipay_user_id","2088345012230098");
        //bizContent.put("identity_params",identityParams);

        //// 设置扩展参数
        //JSONObject extraParam = new JSONObject();
        //extraParam.put("category","CHARGE_PILE_CAR");
        //extraParam.put("serviceId","2020042800000000000001450466");
        //bizContent.put("extra_param",extraParam);

        // 设置整体请求参数
        request.setBizContent(bizContent.toString());

        // 使用sdkExecute方法发起请求
        AlipayFundAuthOrderAppFreezeResponse response = alipayClient.sdkExecute(request);
        String orderStr = response.getBody();

        if(response.isSuccess()){
            return orderStr;
        } else {
            return "";
        }
    }





    /*******以下为identity_hash生成加密串的方法示例，无实名校验诉求可忽略********/
    /**
     * 根据给定的一个或多个字符串获得摘要
     * 使用SHA256摘要方式与UTF8编码,返回十六进制的字符串
     *
     * @param strsToBeDigest
     * @return  十六进制的字符串
     */
    private static String genHashCode(String algorithmType, String charset, String... strsToBeDigest) {
        //拼接字符串,再hash
        StringBuilder sb = new StringBuilder();
        for (String str : strsToBeDigest) {
            sb.append(str);
        }
        String identity = sb.toString();
        MessageDigest messageDigest;
        String hashResult = "";
        try {
            messageDigest = MessageDigest.getInstance(algorithmType);
            byte[] bytes = messageDigest.digest(identity.getBytes(charset));
            hashResult = convertByteToHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            System.out.println("获得实名hash值出错,无此hash算法");
        } catch (UnsupportedEncodingException e) {
            System.out.println("获得实名hash值出错,不支持此编码");
        }
        return hashResult;
    }

    /**
     * 将字节数组转为十六进制字符串
     *
     * @param bytes
     * @return
     */
    private static String convertByteToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String byteString;
        for (byte aByte : bytes) {
            //byte转为int时高位补零
            byteString = Integer.toHexString(aByte & 0xFF);
            if (byteString.length() == 1) {
                //补齐2位
                sb.append("0");
            }
            sb.append(byteString);
        }
        return sb.toString();
    }




}
